<template>
	<view class="container">
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input-wrapper">
				<uni-icons type="search" size="18" color="#6B7280" />
				<input 
					class="search-input" 
					type="text" 
					placeholder="搜索日程..." 
					v-model="searchKeyword"
					@input="onSearchInput"
				/>
				<uni-icons 
					v-if="searchKeyword" 
					type="clear" 
					size="16" 
					color="#6B7280" 
					@click="clearSearch"
				/>
			</view>
		</view>

		<!-- 筛选栏 -->
		<view class="filter-bar">
			<view class="filter-row">
				<!-- 时间范围筛选 -->
				<view class="filter-group">
					<view class="filter-label">时间范围</view>
					<picker 
						:value="getPickerIndex('dateRange')" 
						:range="dateRangeOptions"
						range-key="label"
						@change="onDateRangeChange"
						class="filter-picker"
					>
						<view class="picker-display">
							{{ getCurrentLabel('dateRange') }}
							<uni-icons type="bottom" size="14" color="#6B7280" />
						</view>
					</picker>
				</view>
				
				<!-- 类型筛选 -->
				<view class="filter-group">
					<view class="filter-label">类型</view>
					<picker 
						:value="getPickerIndex('type')" 
						:range="typeOptions"
						range-key="label"
						@change="onTypeChange"
						class="filter-picker"
					>
						<view class="picker-display">
							{{ getCurrentLabel('type') }}
							<uni-icons type="bottom" size="14" color="#6B7280" />
						</view>
					</picker>
				</view>
				
				<!-- 优先级筛选 -->
				<view class="filter-group">
					<view class="filter-label">优先级</view>
					<picker 
						:value="getPickerIndex('priority')" 
						:range="priorityOptions"
						range-key="label"
						@change="onPriorityChange"
						class="filter-picker"
					>
						<view class="picker-display">
							{{ getCurrentLabel('priority') }}
							<uni-icons type="bottom" size="14" color="#6B7280" />
						</view>
					</picker>
				</view>
			</view>
		</view>

		<!-- 日程列表 -->
		<view class="schedule-list">
			<view v-if="filteredSchedules.length === 0" class="empty-state">
				<uni-icons type="calendar" size="64" color="#D1D5DB" />
				<text class="empty-text">暂无日程</text>
				<text class="empty-desc">点击右下角按钮添加新日程</text>
			</view>
			
			<view v-else>
				<schedule-card 
					v-for="schedule in filteredSchedules" 
					:key="schedule.id"
					:schedule="schedule"
					@toggle-completed="handleToggleCompleted"
					@hide-completed="handleHideCompleted"
					@edit="editSchedule"
					@delete="handleDeleteSchedule"
				/>
			</view>
			
			<!-- 查看已完成事项按钮 -->
			<view class="completed-items-btn" @click="viewCompletedItems" v-if="completedCount > 0">
				<uni-icons type="checkmarkempty" size="16" color="#10B981" />
				<text class="completed-text">查看已完成事项 ({{ completedCount }})</text>
				<uni-icons type="right" size="14" color="#6B7280" />
			</view>
		</view>

		<!-- 浮动添加按钮 -->
		<view class="fab" @click="createSchedule">
			<uni-icons type="plus" size="24" color="#FFFFFF" />
		</view>
	</view>
</template>

<script>
/**
 * 首页组件
 * 显示日程列表，支持搜索、筛选、完成等操作
 */
import { mapState, mapGetters, mapActions } from 'vuex'
import ScheduleCard from '../../components/ScheduleCard.vue'

export default {
	name: 'IndexPage',
	
	components: {
		ScheduleCard
	},
	
	data() {
		return {
			/** 搜索关键词 */
			searchKeyword: '',
			
			// ========== 筛选选项配置 ==========
			/** 时间范围筛选选项 */
			dateRangeOptions: [
				{ value: 'all', label: '全部' },
				{ value: 'today', label: '今天' },
				{ value: 'tomorrow', label: '明天' },
				{ value: 'week', label: '本周' }
			],
			/** 类型筛选选项 */
			typeOptions: [
				{ value: 'all', label: '全部' },
				{ value: 'schedule', label: '日程' },
				{ value: 'task', label: '任务' }
			],
			/** 优先级筛选选项 */
			priorityOptions: [
				{ value: 'all', label: '全部' },
				{ value: 'urgent', label: '紧急' },
				{ value: 'high', label: '高' },
				{ value: 'medium', label: '中' },
				{ value: 'low', label: '低' }
			]
		}
	},
	
	computed: {
		...mapState('schedule', ['filters']),
		...mapGetters('schedule', ['filteredSchedules', 'completedSchedules']),
		completedCount() {
			return this.completedSchedules.length;
		}
	},
	
	async onLoad() {
		// 加载数据
		await this.loadSchedules()
		await this.loadSettings()
		
		// 初始化日程提醒服务
		await this.initReminderService()
	},
	
	onShow() {
		// 页面显示时刷新数据
		this.refreshData()
		
		// 更新自定义tabBar选中状态
		if (typeof this.getTabBar === 'function' && this.getTabBar()) {
			this.getTabBar().selected = 0
		}
	},
	
	// 下拉刷新
	onPullDownRefresh() {
		this.refreshData()
		setTimeout(() => {
			uni.stopPullDownRefresh()
		}, 1000)
	},
	
	// 页面卸载时停止提醒检查器
	onUnload() {
		this.clearAllReminders()
	},
	
	methods: {
		...mapActions('schedule', ['loadSchedules', 'toggleCompleted', 'deleteSchedule', 'initReminderService', 'clearAllReminders']),
		...mapActions('settings', ['loadSettings']),
		
		// 搜索输入
		onSearchInput(e) {
			const keyword = e.detail.value
			this.$store.commit('schedule/SET_SEARCH_KEYWORD', keyword)
		},
		
		// 清除搜索
		clearSearch() {
			this.searchKeyword = ''
			this.$store.commit('schedule/SET_SEARCH_KEYWORD', '')
		},
		
		// 设置筛选条件
		setFilter(type, value) {
			const currentValue = this.filters[type]
			const newValue = currentValue === value ? (type === 'dateRange' ? 'all' : 'all') : value
			
			this.$store.commit('schedule/SET_FILTERS', {
				[type]: newValue
			})
		},
		
		// 获取当前筛选值对应的选项索引
		getPickerIndex(type) {
			const options = this[`${type}Options`]
			const currentValue = this.filters[type]
			return options.findIndex(option => option.value === currentValue)
		},
		
		// 获取当前筛选值对应的显示标签
		getCurrentLabel(type) {
			const options = this[`${type}Options`]
			const currentValue = this.filters[type]
			const option = options.find(option => option.value === currentValue)
			return option ? option.label : '全部'
		},
		
		// 时间范围改变事件
		onDateRangeChange(e) {
			const index = e.detail.value
			const value = this.dateRangeOptions[index].value
			this.$store.commit('schedule/SET_FILTERS', {
				dateRange: value
			})
		},
		
		// 类型改变事件
		onTypeChange(e) {
			const index = e.detail.value
			const value = this.typeOptions[index].value
			this.$store.commit('schedule/SET_FILTERS', {
				type: value
			})
		},
		
		// 优先级改变事件
		onPriorityChange(e) {
			const index = e.detail.value
			const value = this.priorityOptions[index].value
			this.$store.commit('schedule/SET_FILTERS', {
				priority: value
			})
		},
		
		// 处理完成状态切换
		async handleToggleCompleted(scheduleId) {
			try {
				await this.toggleCompleted(scheduleId)
				uni.showToast({
					title: '状态已更新',
					icon: 'success',
					duration: 1500
				})
			} catch (error) {
				uni.showToast({
					title: '操作失败',
					icon: 'error'
				})
			}
		},
		
		// 处理隐藏已完成事项
		handleHideCompleted(scheduleId) {
			this.$store.commit('schedule/TOGGLE_HIDDEN_SCHEDULE', scheduleId);
			uni.showToast({
				title: '已隐藏',
				icon: 'success',
				duration: 1500
			});
		},

		// 查看已完成事项
		viewCompletedItems() {
			uni.navigateTo({
				url: `/pages/completed/completed?filter=${JSON.stringify(this.filters)}`
			});
		},
		
		// 编辑日程
		editSchedule(schedule) {
			uni.navigateTo({
				url: `/pages/create/create?id=${schedule.id}&mode=edit`
			})
		},
		
		// 处理删除日程
		async handleDeleteSchedule(scheduleId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个日程吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await this.deleteSchedule(scheduleId)
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							})
						} catch (error) {
							uni.showToast({
								title: '删除失败',
								icon: 'error'
							})
						}
					}
				}
			})
		},
		
		// 创建新日程
		createSchedule() {
			uni.navigateTo({
				url: '/pages/create/create?mode=create'
			})
		},
		
		// 刷新数据
		async refreshData() {
			await this.loadSchedules()
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: $background-gray;
	padding-bottom: 64px; // 为底部导航栏留空间
}

.search-bar {
	background-color: $card-white;
	padding: $spacing-lg;
	border-bottom: 1px solid $border-gray;
}

.search-input-wrapper {
	display: flex;
	align-items: center;
	background-color: $background-gray;
	border-radius: $border-radius-md;
	padding: 0 $spacing-lg;
	height: 40px;
}

.search-input {
	flex: 1;
	margin-left: $spacing-sm;
	font-size: $font-size-body;
	color: $text-dark-gray;
	
	&::placeholder {
		color: $text-light-gray;
	}
}

.filter-bar {
	background-color: $card-white;
	border-bottom: 1px solid $border-gray;
	padding: $spacing-lg;
}

.filter-row {
	display: flex;
	gap: $spacing-md;
	align-items: flex-end; // 底部对齐
}

.filter-group {
	flex: 1;
	min-width: 0; // 允许内容压缩
}

.filter-label {
	font-size: $font-size-caption;
	color: $text-light-gray;
	margin-bottom: $spacing-xs;
	font-weight: 500;
}

.filter-picker {
	width: 100%;
}

.picker-display {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: $spacing-sm $spacing-md;
	background-color: $background-gray;
	border-radius: $border-radius-md;
	border: 1px solid $border-gray;
	font-size: $font-size-body;
	color: $text-dark-gray;
	height: 40px;
	transition: all 0.2s ease;
	
	&:active {
		background-color: #F3F4F6;
		border-color: $primary-blue;
	}
}

/* 响应式设计 */
@media (max-width: 768px) {
	.filter-row {
		gap: $spacing-xs; // 减小间距
	}
	
	.filter-label {
		font-size: 11px;
		margin-bottom: 4px;
	}
	
	.picker-display {
		padding: 6px $spacing-xs;
		height: 36px;
		font-size: 12px;
	}
}

@media (max-width: 480px) {
	.filter-row {
		gap: 6px; // 进一步减小间距，保持横向布局
	}
	
	.filter-group {
		flex: 1;
		min-width: 0; // 允许内容压缩
	}
	
	.filter-label {
		font-size: 10px;
		margin-bottom: 3px;
		white-space: nowrap; // 防止标签换行
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	.picker-display {
		padding: 4px 6px;
		height: 32px;
		font-size: 11px;
		min-width: 0; // 允许内容压缩
	}
}

.schedule-list {
	padding: $spacing-lg;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px $spacing-lg;
	text-align: center;
}

.empty-text {
	margin-top: $spacing-lg;
	font-size: $font-size-title-2;
	font-weight: $font-weight-semibold;
	color: $text-dark-gray;
}

.empty-desc {
	margin-top: $spacing-sm;
	font-size: $font-size-body;
	color: $text-light-gray;
}

.completed-items-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: $spacing-sm $spacing-md;
	background-color: $background-gray;
	border-radius: $border-radius-md;
	border: 1px solid $border-gray;
	font-size: $font-size-body;
	color: $text-dark-gray;
	margin-top: $spacing-md;
	
	&:active {
		background-color: #F3F4F6;
		border-color: $primary-blue;
	}
}

.completed-text {
	flex: 1;
	margin: 0 $spacing-sm;
	font-size: $font-size-body;
	color: $text-dark-gray;
}

.fab {
	position: fixed;
	right: $spacing-lg;
	bottom: 100px; // 避开底部导航栏
	width: 56px;
	height: 56px;
	background-color: $primary-blue;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: $shadow-md;
	z-index: 999;
	
	&:active {
		transform: scale(0.95);
		transition: transform 0.1s;
	}
}
</style>
